﻿#include "largefileuploaddao.h"
#include <QCoreApplication>
#include <QDebug>
#include <QSqlError>
#include <QSqlQuery>

static QString guid()
{
    QUuid id = QUuid::createUuid();
    QString strGuid = id.toString();
    strGuid = id.toString(QUuid::Id128);
    return strGuid;
}
static QString createMulitipleFolders(QString path)
{
    QDir dir(path);
    if (dir.exists(path))
    {
        return path;
    }
    QString parentDir = createMulitipleFolders(path.mid(0, path.lastIndexOf('/')));
    QString dirName = path.mid(path.lastIndexOf('/') + 1);
    QDir parentPath(parentDir);
    if (!dirName.isEmpty())
    {
        parentPath.mkdir(dirName);
    }
    return parentDir + "/" + dirName;
}

LargeFileUploadDao::LargeFileUploadDao()
{
    tableName = "large_file";
    QString dbDir = QCoreApplication::applicationDirPath() + "/database";
    createMulitipleFolders(dbDir);
    dbPath = dbDir + "/largeFileUpload.db";
    dataBase = QSqlDatabase::addDatabase("QSQLITE", QString("connect_%1").arg(guid()));
}

LargeFileUploadDao::~LargeFileUploadDao()
{
    closeDataBase();
}

void LargeFileUploadDao::openDataBase()
{

    dataBase.setDatabaseName(dbPath);
    dataBase.open();

    QSqlQuery sql_query(dataBase);
    QString strSql = QString("select * from %1").arg(tableName);
    if (!sql_query.exec(strSql))
    {
//        qCritical() << __FUNCTION__ << sql_query.lastError();
        strSql = QString("create table %1("
                         "id integer primary key,"
                         "md5 text,"
                         "fileName text,"
                         "absolutePath text,"
                         "uploadedSize integer,"
                         "totalSize integer,"
                         "uploadStatus integer)")
                     .arg(tableName);
        if (!sql_query.exec(strSql))
            qCritical() << __FUNCTION__ << sql_query.lastError();
    }
}

void LargeFileUploadDao::closeDataBase()
{
    if (dataBase.isOpen())
        dataBase.close();
}

QSqlDatabase LargeFileUploadDao::getDataBase() const
{
    return dataBase;
}

QString LargeFileUploadDao::getDbPath() const
{
    return dbPath;
}

void LargeFileUploadDao::setDbPath(const QString &value)
{
    dbPath = value;
}

bool LargeFileUploadDao::selectLargeFileUploadByMd5(LargeFileUpload &largeFileUpload,QString &md5)
{
    bool res = true;
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("select * from %1 where md5='%2'")
                         .arg(tableName)
                         .arg(md5);
    if (sql_query.exec(sqlStr))
    {
        if (sql_query.next())
        {
            largeFileUpload.setId(sql_query.value(0).toULongLong());
            largeFileUpload.setMd5(sql_query.value(1).toString());
            largeFileUpload.setFileName(sql_query.value(2).toString());
            largeFileUpload.setAbsolutePath(sql_query.value(3).toString());
            largeFileUpload.setUploadedSize(sql_query.value(4).toULongLong());
            largeFileUpload.setTotalSize(sql_query.value(5).toULongLong());
            largeFileUpload.setUploadStatus(sql_query.value(6).toUInt());
        }
        else
        {
            res = false;
            qCritical() << __FUNCTION__ << "not find by md5!" << sqlStr;
        }
    }
    else
    {
        res = false;
        qCritical() << __FUNCTION__ << sql_query.lastError();
    }
    return res;
}

bool LargeFileUploadDao::saveLargeFileUpload(LargeFileUpload &largeFileUpload)
{
    bool res = true;
    if (largeFileUpload.getId() == 0)
    {
        QSqlQuery sql_query(dataBase);
        QString sqlStr = QString("insert into %1(md5,fileName,absolutePath,uploadedSize,totalSize,uploadStatus) values('%2','%3','%4',%5,%6,%7)")
                             .arg(tableName)
                             .arg(largeFileUpload.getMd5())
                             .arg(largeFileUpload.getFileName())
                             .arg(largeFileUpload.getAbsolutePath())
                             .arg(largeFileUpload.getUploadedSize())
                             .arg(largeFileUpload.getTotalSize())
                             .arg(largeFileUpload.getUploadStatus());
        if (!sql_query.exec(sqlStr))
        {
            qCritical() << __FUNCTION__ << sql_query.lastError();
            res = false;
        }
        else
        {
            qDebug () << sqlStr;
            //返回刚刚添加的对象
            QThread::msleep(100);
            QString md5 = largeFileUpload.getMd5();
            selectLargeFileUploadByMd5(largeFileUpload,md5);
        }
    }
    else
    {
        QSqlQuery sql_query(dataBase);
        QString sqlStr = QString("update %1 set ").arg(tableName);
        if (!largeFileUpload.getMd5().isEmpty())
        {
            sqlStr.append(QString("md5 = '%1', ").arg(largeFileUpload.getMd5()));
        }
        if (!largeFileUpload.getFileName().isEmpty())
        {
            sqlStr.append(QString("fileName = '%1', ").arg(largeFileUpload.getFileName()));
        }
        if (!largeFileUpload.getAbsolutePath().isEmpty())
        {
            sqlStr.append(QString("absolutePath = '%1', ").arg(largeFileUpload.getAbsolutePath()));
        }
        if (largeFileUpload.getUploadedSize() != 0)
        {
            sqlStr.append(QString("uploadedSize = %1, ").arg(largeFileUpload.getUploadedSize()));
        }
        if (largeFileUpload.getTotalSize() != 0)
        {
            sqlStr.append(QString("totalSize = %1, ").arg(largeFileUpload.getTotalSize()));
        }
        sqlStr.append(QString("uploadStatus = %1 ").arg(largeFileUpload.getUploadStatus()));
        sqlStr.append(QString("where id = %1").arg(largeFileUpload.getId()));
        if (!sql_query.exec(sqlStr))
        {
            qCritical() << __FUNCTION__ << sql_query.lastError() << sqlStr;
            res = false;
        }
    }
    return res;
}

bool LargeFileUploadDao::deleteLargeFileUploadById(uint64_t &id)
{
    bool res = true;
    QSqlQuery sql_query(dataBase);
    QString sqlStr = QString("delete from %1 where id=%2")
                         .arg(tableName)
                         .arg(QString::number(id));
    if (!sql_query.exec(sqlStr))
    {
        qCritical() << __FUNCTION__ << sql_query.lastError();
        res = false;
    }
    return res;
}
